package ar.com.spsolutions.splilabrary.view.utils;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;

public class ReflectionUtils {

	protected static final Logger LOG = Logger.getLogger(ReflectionUtils.class);

	private ReflectionUtils() {
		// reduce visibility
	}

	public static Method getMethod(final Class<?> target, final String name,
			final Object... params) {
		if (target == null) {
			return null;
		}
		try {
			return target.getDeclaredMethod(name,
					ReflectionUtils.toClasses(params));
		} catch (final SecurityException e) {
			return null;
		} catch (final NoSuchMethodException e) {
			return ReflectionUtils.getMethod(target.getSuperclass(), name,
					params);
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> Object invoke(final Method method, final Object target,
			final Object... params) {
		if (method == null) {
			return null;
		}
		T result = null;
		final boolean isAccesible = method.isAccessible();
		method.setAccessible(true);
		try {
			result = (T) method.invoke(target, params);
		} catch (final Exception e) {
			ReflectionUtils.LOG.info(e.getMessage());
			return null;
		}
		method.setAccessible(isAccesible);
		return result;
	}

	private static Class<?>[] toClasses(final Object[] params) {
		final Class<?>[] result = new Class<?>[params.length];
		for (int i = 0; i < params.length; i++) {
			result[i] = params[i].getClass();
		}
		return result;
	}
}
